<template class="search-container">
  <div>
    <!-- 搜索栏 -->
    <!-- Tips: 在 van-search 外层增加 form 标签，
    且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form action="/" class="search-form">
  <van-search
    v-model="shosuoText"
    show-action
    background="blue"
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @cancel="onCancel"
    @focus="isSearch = false"
  />
</form>
    <!-- 搜索栏 -->

<!-- 搜索结果 -->
<ShoSuoResult v-if="isSearch"
  :shosuo-text="shosuoText"
 />

  <!-- 联想建议 -->
<ShoSuoSuggestion
v-else-if="shosuoText"
 :shosuo-text="shosuoText"
 @search="onSearch"
/>

  <!-- 搜索历史记录 -->
<ShoSuoHistory
 v-else
 :search-histories="searchHistories"
 @clear-search-history="searchHistories = []"
 @Search="onSearch"
/>

  </div>
</template>

<script>
import ShoSuoSuggestion from './components/shosuo-suggestion.vue'
import ShoSuoResult from './components/shosuo-result.vue'
import ShoSuoHistory from './components/shosuo-history'
import { setItem, getItem } from '@/utlis/storage'
export default {
  components: {
    ShoSuoSuggestion,
    ShoSuoResult,
    ShoSuoHistory
  },
  name: 'ShoSuo',
  data () {
    return {
      shosuoText: '',
      isSearch: false, // 控制搜索结果的展示
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || [] // 搜索的历史记录
    }
  },
  methods: {
    onSearch (val) {
      // 更新文本框内容
      this.shosuoText = val

      // 存储搜索历史记录
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)

      // 渲染搜索结果
      this.isSearch = true
    },
    onCancel () {
      this.$router.back()
    }
  },
  watch: {
    searchHistories (val) {
      console.log('嘻嘻')
      setItem('TOUTIAO_SEARCH_HISTORIES', val)
    }
  }

}
</script>

<style scoped lang="less">
.search-container{
  padding: 108px;
}
.search-form{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1;
}

</style>
